<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\common;
use think\facade\Db;
class Order
{
	//订单退款  1余额支付 2微信支付 3支付宝支付 4货到付款 11百度小程序 12头条小程序
	public static function refund($order,$refund_money,$reason='退款'){
		if(!$reason) $reason = '退款';
		$paytype = $order['paytypeid'];
		if(!$paytype) return ['status'=>1,'msg'=>''];
		if($refund_money == 0) return ['status'=>1,'msg'=>''];
		if($paytype == 1){
		    //如果是代付则退回代付账号,不可以用orderid[]
            $payorder = Db::name('payorder')->where('aid',$order['aid'])->where('ordernum',$order['ordernum'])->find();
            if($payorder && $payorder['paymid']){
                $mid = $payorder['paymid'];
                $remark = '代付订单退款';
            }else{
                $mid = $order['mid'];
                $remark = '订单退款';
            }
			$rs = \app\common\Member::addmoney($order['aid'],$mid,$refund_money,$remark.' '.$reason);
		}
		if(strpos($order['ordernum'],'_')){ //合并支付
			$ordernum = explode('_',$order['ordernum'])[0];
			$payorder = Db::name('payorder')->where('aid',$order['aid'])->where('ordernum',$ordernum)->find();
			if($payorder['status']==1){ //是合并支付的
				$order['totalprice'] = $payorder['money'];
				$order['ordernum'] = $ordernum;
			}
		}
		if($paytype == 2){
			$rs = \app\common\Wxpay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($paytype == 3){
			$rs = \app\common\Alipay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($paytype == 4){
			$rs = ['status'=>1,'msg'=>''];
		}
		//转账汇款
        if($paytype == 5){
            $rs = ['status'=>1,'msg'=>''];
        }
		if($order['paytypeid'] == 11){ //百度小程序
			$rs = \app\common\Baidupay::refund($order['aid'],$order['mid'],$order['ordernum'],$order['paynum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 12){ //头条小程序
			$rs = \app\common\Ttpay::refund($order['aid'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 22){ //云收银
			$rs = \app\common\Yunpay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 23){
			$rs = \app\common\Qmpay::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 24){
			$rs = \app\common\Qmpay::refund2($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 51){  //paypal
			$rs = \app\custom\PayPal::refund($order['aid'],$order['platform'],$order['ordernum'],$order['totalprice'],$refund_money,$reason);
		}
		if($order['paytypeid'] == 60){ //视频号
			$rs = ['status'=>1,'msg'=>''];
		}
		return $rs;
	}
	//订单收货
	public static function collect($order,$type='shop',$commission_mid = 0){
		$aid = $order['aid'];
		$mid = $order['mid'];
        if($type == 'shop'){
			if($order['fromwxvideo'] == 1){
				\app\common\Wxvideo::deliveryrecieve($order['id']);
			}

			$oglist = Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->select()->toArray();
            if($order['bid']!=0){//入驻商家的货款
				$totalnum = 0;
				foreach($oglist as $og){
					$totalnum += $og['num'];
				}
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$totalcommission = 0;
					$og_business_money = false;
					$totalmoney = 0;
					foreach($oglist as $og){
						//if($og['iscommission']) continue;
						if($og['parent1'] && $og['parent1commission'] > 0){
							$totalcommission += $og['parent1commission'];
						}
						if($og['parent2'] && $og['parent2commission'] > 0){
							$totalcommission += $og['parent2commission'];
						}
						if($og['parent3'] && $og['parent3commission'] > 0){
							$totalcommission += $og['parent3commission'];
						}
						if(!is_null($og['business_total_money'])) {
							$og_business_money = true;
							$totalmoney += $og['business_total_money'];
						}
					}
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$bset = Db::name('business_sysset')->where('aid',$aid)->find();
					if($bset['commission_kouchu'] == 0){ //不扣除佣金
						$totalcommission = 0;
					}
					//商品独立费率
					if($og_business_money) {
						if(false){}else{
							$totalmoney = $totalmoney + $order['freight_price'] - $totalcommission;
						}
                        $totalmoney = $totalmoney - $order['refund_money'];
					} else {
						if(false){}else{
							$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['manjia_money'] - $order['refund_money'] - $totalcommission;
							if($totalmoney > 0){
								$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
							}
						}
					}

					if($order['paytypeid']==4){
						$totalmoney = $totalmoney - $order['totalprice'];
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，订单号：'.$order['ordernum'],true);
				}
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$totalnum)->update();
                //Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->update(['iscommission' => 1]);
                }
            //赠积分
            if($order['givescore'] > 0){
                \app\common\Member::addscore($aid,$order['mid'],$order['givescore'],'购买产品赠送'.t('积分'));
            }

            //购物返现
			$cashbacklist = Db::name('cashback')
				->where('aid',$aid)
				->where('bid',$order['bid'])
				->where('starttime','<',$order['paytime'])
				->where('endtime','>',$order['paytime'])
				->order('sort desc')->select()->toArray();

			//查询购买用户
			$member = Db::name('member')
				->where('id',$order['mid'])
				//->field('levelid')
				->find();

			if($oglist && $member && $cashbacklist){

				foreach($oglist as $og){
					$product = Db::name('shop_product')
						->where('id',$og['proid'])
						->field('id,cid')
						->find();

					if($product){

						foreach($cashbacklist as $v){

							$gettj = explode(',',$v['gettj']);
							if(!in_array('-1',$gettj) && !in_array($member['levelid'],$gettj)){ //不是所有人
								continue;
							}

							if($v['fwtype']==2){//指定商品可用
								$productids = explode(',',$v['productids']);
								if(!in_array($product['id'],$productids)){
									continue;
								}
							}

							if($v['fwtype']==1){//指定类目可用
								$categoryids = explode(',',$v['categoryids']);
								$cids = explode(',',$product['cid']);
								$clist = Db::name('shop_category')->where('pid','in',$categoryids)->select()->toArray();
								foreach($clist as $vc){
									$categoryids[] = $vc['id'];
									$cate2 = Db::name('shop_category')->where('pid',$vc['id'])->find();
									$categoryids[] = $cate2['id'];
								}
								if(!array_intersect($cids,$categoryids)){
									continue;
								}
							}

							//如果返现利率大于0
							if($v['back_ratio']>0){
								//计算返现
								$back_price = $v['back_ratio']*$og['real_totalprice']/100;

								//返现类型 1、余额 2、佣金 3、积分
								if($v['back_type'] == 1 || $v['back_type']== 2){
									$back_price = round($back_price,2);
								}

								if($v['back_type'] == 3){

									$back_price = round($back_price);
								}
								if($back_price>0){
									if($v['back_type'] == 1 ){

										\app\common\Member::addmoney($aid,$order['mid'],$back_price,$v['name']);
									}
									if($v['back_type'] == 2){

										\app\common\Member::addcommission($aid,$order['mid'],$order['mid'],$back_price,$v['name']);
									}
									if($v['back_type'] == 3){
										\app\common\Member::addscore($aid,$order['mid'],$back_price,$v['name']);
									}
								}
							}

						}
					}
				}
			}

			}elseif($type=='collage'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$totalmoney = 0;
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					if(false){}else{
						if(!is_null($order['business_total_money'])) {
							$totalmoney = $order['business_total_money'];
						} else {
							$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['leader_money'];
							if($totalmoney > 0){
								$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
							}
						}
					}
					if($order['paytypeid']==4){
						$totalmoney = $totalmoney - $order['totalprice'];
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，拼团订单号：'.$order['ordernum'],true);
				}
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}elseif($type=='cycle'){
            if($order['bid']!=0){//入驻商家的货款
                $isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
                if(!$isbusinesspay){
                    $totalmoney = 0;
                    $binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
                    if(false){}else{
                        if(!is_null($order['business_total_money'])) {
                            $totalmoney = $order['business_total_money'];
                        } else {
                            $totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['leader_money'];
                            if($totalmoney > 0){
                                $totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
                            }
                        }
                    }
                    if($order['paytypeid']==4){
                        $totalmoney = $totalmoney - $order['totalprice'];
                    }
                    if($totalmoney < 0){
                        $bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
                        if($bmoney + $totalmoney < 0){
                            return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
                        }
                    }
                    \app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，周期购订单号：'.$order['ordernum'],true);
                }
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
            }
        }elseif($type=='yuyue'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					if(false){}else{
						$totalmoney = $order['product_price'];
					}
					if($totalmoney > 0){
						$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					$worker_order = Db::name('yuyue_worker_order')->where('id',$order['worker_orderid'])->find();
					if(false){}else{
						$worker = Db::name('yuyue_worker')->where('id',$worker_order['worker_id'])->find();
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'服务订单/('.$worker['realname'].')'.$worker['tel'].' /:'.$order['ordernum'],true);
				}
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}elseif($type=='lucky_collage'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalcommission = 0;
					//if($order['iscommission']){
					if($order['parent1'] && $order['parent1commission'] > 0){
						$totalcommission += $order['parent1commission'];
					}
					if($order['parent2'] && $order['parent2commission'] > 0){
						$totalcommission += $order['parent2commission'];
					}
					if($order['parent3'] && $order['parent3commission'] > 0){
						$totalcommission += $order['parent3commission'];
					}
					//}
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$bset = Db::name('business_sysset')->where('aid',$aid)->find();
					if($bset['commission_kouchu'] == 0){ //不扣除佣金
						$totalcommission = 0;
					}

					if(false){}else{
						$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['leader_money'] - $totalcommission;
						if($totalmoney > 0){
							$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
						}
					}
					if($order['paytypeid']==4){
						$totalmoney = $totalmoney - $order['totalprice'];
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，幸运拼团订单号：'.$order['ordernum'],true);
				}
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}elseif($type=='kanjia'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					if(false){}else{
						if(!is_null($order['business_total_money'])) {
							$totalmoney = $order['business_total_money'];
						} else {
							$totalmoney = $order['product_price'] + $order['freight_price'];
							if($totalmoney > 0){
								$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
							}
						}
					}
					if($order['paytypeid']==4){
						$totalmoney = $totalmoney - $order['totalprice'];
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，砍价订单号：'.$order['ordernum'],true);
				}
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}elseif($type=='seckill'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$totalcommission = 0;
					if($order['parent1'] && $order['parent1commission'] > 0){
						$totalcommission += $order['parent1commission'];
					}
					if($order['parent2'] && $order['parent2commission'] > 0){
						$totalcommission += $order['parent2commission'];
					}
					if($order['parent3'] && $order['parent3commission'] > 0){
						$totalcommission += $order['parent3commission'];
					}
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$bset = Db::name('business_sysset')->where('aid',$aid)->find();
					if($bset['commission_kouchu'] == 0){ //不扣除佣金
						$totalcommission = 0;
					}
					if(false){}else{
						if(!is_null($order['business_total_money'])) {
							$totalmoney = $order['business_total_money'] - $totalcommission;;
						} else {
							$totalmoney = $order['product_price'] + $order['freight_price'] - $order['coupon_money'] - $order['manjia_money'] - $totalcommission;
							if($totalmoney > 0){
								$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
							}
						}
					}
					if($order['paytypeid']==4){
						$totalmoney = $totalmoney - $order['totalprice'];
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，秒杀订单号：'.$order['ordernum'],true);
				}
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
//                Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$order['id'])->update(['iscommission' => 1]);
            }
            //赠积分
            if($order['givescore'] > 0){
                \app\common\Member::addscore($aid,$order['mid'],$order['givescore'],'购买产品赠送'.t('积分'));
            }
		}elseif($type=='coupon'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalmoney = $order['price'];
					if($totalmoney > 0){
						$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'销售'.t('优惠券').' 订单号：'.$order['ordernum'],true);
				}
			}
		}elseif($type=='maidan'){
			$totalcommission = 0;
			$maidanfenxiao = Db::name('admin_set')->where('aid',$aid)->value('maidanfenxiao');
            if($maidanfenxiao == 1){ //参与分销
				$member = Db::name('member')->where('aid',$aid)->where('id',$order['mid'])->find();
				$agleveldata = Db::name('member_level')->where('aid',aid)->where('id',$member['levelid'])->find();
				if($agleveldata['can_agent'] > 0 && $agleveldata['commission1own']==1){
					$member['pid'] = $member['id'];
				}
				$isCommissionScore = 0;
				$ogdata = [];
                //是否积分提成
                $ogdata['isparent1score'] = 0;
                $ogdata['isparent2score'] = 0;
                $ogdata['isparent3score'] = 0;
				if($member['pid']){
					$parent1 = Db::name('member')->where('aid',$aid)->where('id',$member['pid'])->find();
					if($parent1){
						$agleveldata1 = Db::name('member_level')->where('aid',$aid)->where('id',$parent1['levelid'])->find();
						if($agleveldata1['can_agent']!=0){
							$ogdata['parent1'] = $parent1['id'];
							if($isCommissionScore && $agleveldata1['maidan_commission_score1']>0){
                                $ogdata['isparent1score'] = 1;
                                $ogdata['parent1score'] = round($agleveldata1['maidan_commission_score1'] * $order['paymoney'] * 0.01);
                            }
						}
					}
				}
				if($parent1['pid']){
					$parent2 = Db::name('member')->where('aid',$aid)->where('id',$parent1['pid'])->find();
					if($parent2){
						$agleveldata2 = Db::name('member_level')->where('aid',$aid)->where('id',$parent2['levelid'])->find();
						if($agleveldata2['can_agent']>1){
							$ogdata['parent2'] = $parent2['id'];
                            if($isCommissionScore && $agleveldata2['maidan_commission_score2']>0){
                                $ogdata['isparent2score'] = 1;
                                $ogdata['parent2score'] = round($agleveldata2['maidan_commission_score2'] * $order['paymoney'] * 0.01);
                            }
						}
					}
				}
				if($parent2['pid']){
					$parent3 = Db::name('member')->where('aid',$aid)->where('id',$parent2['pid'])->find();
					if($parent3){
						$agleveldata3 = Db::name('member_level')->where('aid',$aid)->where('id',$parent3['levelid'])->find();
						if($agleveldata3['can_agent']>2){
							$ogdata['parent3'] = $parent3['id'];
                            if($isCommissionScore &&  $agleveldata3['maidan_commission_score3']>0){
                                $ogdata['isparent3score'] = 1;
                                $ogdata['parent3score'] = round($agleveldata3['maidan_commission_score3'] * $order['paymoney'] * 0.01);
                            }
						}
					}
				}
				$ogdata['parent1commission'] = $agleveldata1['commission1'] * $order['paymoney'] * 0.01;
				$ogdata['parent2commission'] = $agleveldata2['commission2'] * $order['paymoney'] * 0.01;
				$ogdata['parent3commission'] = $agleveldata3['commission3'] * $order['paymoney'] * 0.01;
				if($ogdata['parent1'] && $ogdata['isparent1score']==1){
                    $ogdata['parent1score']>0 && \app\common\Member::addscore($aid,$ogdata['parent1'],$ogdata['parent1score'],'下级买单'.t('积分').'奖励');
                }elseif($ogdata['parent1'] && $ogdata['isparent1score']==0 && $ogdata['parent1commission'] > 0){
					$totalcommission+=$ogdata['parent1commission'];
					\app\common\Member::addcommission($aid,$ogdata['parent1'],$mid,$ogdata['parent1commission'],'下级买单付款奖励');
					Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$ogdata['parent1'],'frommid'=>$order['mid'],'orderid'=>$order['id'],'type'=>'maidan','commission'=>$ogdata['parent1commission'],'remark'=>'下级买单付款奖励','createtime'=>time(),'status'=>1,'endtime'=>time()]);
				}
                if($ogdata['parent2'] && $ogdata['isparent2score']==1){
                    $ogdata['parent2score']>0 && \app\common\Member::addscore($aid,$ogdata['parent2'],$ogdata['parent2score'],'下二级买单'.t('积分').'奖励');
                }elseif($ogdata['parent2'] && $ogdata['isparent2score']==0 && $ogdata['parent2commission'] > 0){
					$totalcommission+=$ogdata['parent2commission'];
					\app\common\Member::addcommission($aid,$ogdata['parent2'],$mid,$ogdata['parent2commission'],'下二级买单付款奖励');
					Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$ogdata['parent2'],'frommid'=>$order['mid'],'orderid'=>$order['id'],'type'=>'maidan','commission'=>$ogdata['parent2commission'],'remark'=>'下二级买单付款奖励','createtime'=>time(),'status'=>1,'endtime'=>time()]);
				}
                if($ogdata['parent3'] && $ogdata['isparent3score']==1){
                    $ogdata['parent3score']>0 && \app\common\Member::addscore($aid,$ogdata['parent3'],$ogdata['parent3score'],'下三级买单'.t('积分').'奖励');
                }elseif($ogdata['parent3'] && $ogdata['isparent3score']==0 && $ogdata['parent3commission'] > 0){
					$totalcommission+=$ogdata['parent3commission'];
					\app\common\Member::addcommission($aid,$ogdata['parent3'],$mid,$ogdata['parent3commission'],'下三级买单付款奖励');
					Db::name('member_commission_record')->insert(['aid'=>$aid,'mid'=>$ogdata['parent3'],'frommid'=>$order['mid'],'orderid'=>$order['id'],'type'=>'maidan','commission'=>$ogdata['parent3commission'],'remark'=>'下三级买单付款奖励','createtime'=>time(),'status'=>1,'endtime'=>time()]);
				}
				if($ogdata['parent1']){
					\app\common\Member::uplv($aid,$ogdata['parent1']);
				}
				$bset = Db::name('business_sysset')->where('aid',$aid)->find();
                if($bset['commission_kouchu'] == 0){ //不扣除佣金
                    $totalcommission = 0;
                }
			}

			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalmoney = $order['money'] - $order['couponmoney'] - $totalcommission;
					if($totalmoney > 0){
						$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'买单 订单号：'.$order['ordernum'],true);
				}
			}
		}elseif($type=='designerpage'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalmoney = $order['price'];
					if($totalmoney > 0){
						$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'付费查看页面 订单号：'.$order['ordernum'],true);
				}
			}
		}elseif($type == 'scoreshop') {
            //门店分成
            if($order['mdid'] && $commission_mid) {
                $orderGoods = Db::name($type.'_order_goods')->where('orderid',$order['id'])->select()->toArray();
                foreach ($orderGoods as $og) {
                    if($og['mendian_iscommission'] == 0 && $og['mendian_commission'] > 0 && $og['mendian_score'] > 0){
                        if($og['mendian_commission'] > 0) {
                            \app\common\Member::addcommission($aid, $commission_mid, $order['mid'], $og['mendian_commission'], '门店核销：'.$order['ordernum']);
                        }
                        if($og['mendian_score'] > 0) {
                            \app\common\Member::addscore($aid, $commission_mid, $og['mendian_score'],'门店核销：'.$order['ordernum']);
                        }
                        Db::name($type.'_order_goods')->where('id',$og['id'])->update(['mendian_iscommission' => 1]);
                    }
                }
            }
        }elseif($type=='tuangou'){
            if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalmoney = $order['product_price'] + $order['freight_price'] * (100-$binfo['feepercent_freight']) * 0.01 - $order['coupon_money'] - $order['manjia_money'];
					if($totalmoney > 0){
						$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
					}
					if($order['paytypeid']==4){
						$totalmoney = $totalmoney - $order['totalprice'];
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'货款，团购订单号：'.$order['ordernum'],true);
				}
                //店铺加销量
                Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
            }
        }elseif($type=='kecheng'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalcommission = 0;
					//if($order['iscommission']){
					if($order['parent1'] && $order['parent1commission'] > 0){
						$totalcommission += $order['parent1commission'];
					}
					if($order['parent2'] && $order['parent2commission'] > 0){
						$totalcommission += $order['parent2commission'];
					}
					if($order['parent3'] && $order['parent3commission'] > 0){
						$totalcommission += $order['parent3commission'];
					}
					//}
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$bset = Db::name('business_sysset')->where('aid',$aid)->find();
					if($bset['commission_kouchu'] == 0){ //不扣除佣金
						$totalcommission = 0;
					}

					$totalmoney = $order['totalprice'] - $totalcommission;
					if($totalmoney > 0){
						$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'课程订单号：'.$order['ordernum'],true);
				}
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}elseif($type=='yueke'){
			if($order['bid']!=0){//入驻商家的货款
				$isbusinesspay = Db::name('payorder')->where('aid',$aid)->where('ordernum',$order['ordernum'])->value('isbusinesspay');
				if(!$isbusinesspay){
					$binfo = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->find();
					$totalmoney = $order['product_price'];
					if($totalmoney > 0){
						$totalmoney = $totalmoney * (100-$binfo['feepercent']) * 0.01;
					}
					if($totalmoney < 0){
						$bmoney = Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->value('money');
						if($bmoney + $totalmoney < 0){
							return ['status'=>0,'msg'=>'操作失败,商家余额不足'];
						}
					}
					$worker = Db::name('yuyue_worker')->where('id',$order['workerid'])->find();
					\app\common\Business::addmoney($aid,$order['bid'],$totalmoney,'约课订单/('.$worker['realname'].')'.$worker['tel'].' /:'.$order['ordernum'],true);
				}
				//店铺加销量
				Db::name('business')->where('aid',$aid)->where('id',$order['bid'])->inc('sales',$order['num'])->update();
			}
		}
		$set = Db::name('admin_set')->where('aid',$aid)->find();
		if($set['fxjiesuantime_delaydays'] == '0'){ //确认收货后发佣金
			self::giveCommission($order,$type);
		}
        \app\model\Payorder::afterusecoupon($order['id'],$type,2,$order['ordernum']);
        return ['status'=>1,'msg'=>'操作成功'];
	}

	//结算佣金 设置了延时结算时每小时执行
	public static function jiesuanCommission($aid){
		if(getcustom('fxjiesuantime_perweek')) return;
		$set = Db::name('admin_set')->where('aid',$aid)->find();
		$delaytime = floatval($set['fxjiesuantime_delaydays']) * 86400;
		$dtime = time() - $delaytime;
		$recordList = Db::name('member_commission_record')->where('aid',$aid)->where('status',0)->where('type','in',['shop','seckill','scoreshop','collage','lucky_collage','kecheng','tuangou'])->where('createtime','<',$dtime)->where('createtime','>',$dtime-30*86400)->select()->toArray();
		foreach($recordList as $k=>$record){
			$order = Db::name($record['type'].'_order')->where('id',$record['orderid'])->find();
			if(!$order || $order['status'] == 4){
				Db::name('member_commission_record')->where('id',$record['id'])->update(['status'=>2]);
				continue;
			}
			$status = $order['status'];
			if($record['type'] == 'kecheng' && $status == 1) $status = 3;
			if(($set['fxjiesuantime'] == 0 && $status==3 && $order['paytime'] < $dtime) || ($set['fxjiesuantime'] == 1 && in_array($status,[1,2,3]) && $order['paytime'] < $dtime)){
				self::giveCommission($order,$record['type']);
			}
		}
	}
	//结算佣金 每周几结算
	public static function jiesuanCommissionWeek($aid){
		if(!getcustom('fxjiesuantime_perweek')) return;
		$set = Db::name('admin_set')->where('aid',$aid)->find();
		$week = $set['fxjiesuantime_delaydays'];
		if($week == 0) return;
		if($week == 7) $week = 0;
		if($week != date('w')) return;
		$dtime = strtotime(date('Y-m-d',time()-86400));
		$recordList = Db::name('member_commission_record')->where('aid',$aid)->where('status',0)->where('type','in',['shop','seckill','scoreshop','collage','lucky_collage','kecheng','tuangou'])->where('createtime','<',$dtime)->where('createtime','>',$dtime-30*86400)->select()->toArray();
		foreach($recordList as $k=>$record){
			$order = Db::name($record['type'].'_order')->where('id',$record['orderid'])->find();
			if(!$order || $order['status'] == 4){
				Db::name('member_commission_record')->where('id',$record['id'])->update(['status'=>2]);
				continue;
			}
			$status = $order['status'];
			if($record['type'] == 'kecheng' && $status == 1) $status = 3;
			if(($set['fxjiesuantime'] == 0 && $status==3 && $order['paytime'] < $dtime) || ($set['fxjiesuantime'] == 1 && in_array($status,[1,2,3]) && $order['paytime'] < $dtime)){
				self::giveCommission($order,$record['type']);
			}
		}
	}

	//发放佣金
	public static function giveCommission($order,$type='shop'){
		$aid = $order['aid'];
		if($type == 'shop'){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type','shop')->where('orderid',$order['id'])->where('status',0)->select();
			foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
				$og = Db::name('shop_order_goods')->where('id',$commission_record['ogid'])->find();
				Db::name('shop_order_goods')->where('id',$commission_record['ogid'])->update(['iscommission'=>1]);
				if($commission_record['commission'] > 0){
					$commission = $commission_record['commission'];
					\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission,$commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $og['name']; //商品信息
					$tmplcontent['keyword2'] = (string) $og['sell_price'];//商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
					$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
				}
				if($commission_record['score'] > 0){
					\app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
					$tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['name']; //商品信息
                    $tmplcontent['keyword2'] = (string) $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
				}
			}
        }elseif($type=='seckill'){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type','seckill')->where('orderid',$order['id'])->where('status',0)->select();
			foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
				if($commission_record['commission'] > 0){
					\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $order['proname']; //商品信息
					$tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
					$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
				}
				if($commission_record['score'] > 0){
					\app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
					$tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $order['proname']; //商品信息
                    $tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
				}
			}
		}elseif($type == 'scoreshop'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order_goods')->where('id',$commission_record['ogid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['name']; //商品信息
                    $tmplcontent['keyword2'] = (string) $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['name']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type == 'collage'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type == 'kanjia'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['product_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['product_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type == 'lucky_collage'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }

            }
        }elseif($type == 'kecheng'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
                Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }
            }
        }elseif($type=='tuangou'){
			$commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
			foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
				if($commission_record['commission'] > 0){
					\app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
					$tmplcontent = [];
					$tmplcontent['first'] = '恭喜您，成功分销商品获得'.t('佣金').'：￥'.$commission_record['commission'];
					$tmplcontent['remark'] = '点击进入查看~';
					$tmplcontent['keyword1'] = $order['proname']; //商品信息
					$tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
					$tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
					$tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
					$rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
				}
				if($commission_record['score'] > 0){
					\app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
					$tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销商品获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $order['proname']; //商品信息
                    $tmplcontent['keyword2'] = (string) $order['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
					//$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
				}
			}
		}elseif($type == 'yuyue'){
            //佣金
            $commission_record_list = Db::name('member_commission_record')->where('aid',$aid)->where('type',$type)->where('orderid',$order['id'])->where('status',0)->select();
            foreach($commission_record_list as $commission_record){
				Db::name('member_commission_record')->where('id',$commission_record['id'])->update(['status'=>1,'endtime'=>time()]);
                $og = Db::name($type.'_order')->where('id',$commission_record['orderid'])->find();
                if($commission_record['commission'] > 0){
                    \app\common\Member::addcommission($aid,$commission_record['mid'],$commission_record['frommid'],$commission_record['commission'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得'.t('佣金').'：￥'.$commission_record['commission'];
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['commission'].'元';//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    $tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    $rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess',['money'=>$commission_record['commission']]);
                }
                if($commission_record['score'] > 0){
                    \app\common\Member::addscore($aid,$commission_record['mid'],$commission_record['score'],$commission_record['remark']);
                    $tmplcontent = [];
                    $tmplcontent['first'] = '恭喜您，成功分销服务获得：'.$commission_record['score'].t('积分');
                    $tmplcontent['remark'] = '点击进入查看~';
                    $tmplcontent['keyword1'] = $og['proname']; //商品信息
                    $tmplcontent['keyword2'] = $og['sell_price'];//商品单价
                    $tmplcontent['keyword3'] = $commission_record['score'].t('积分');//商品佣金
                    $tmplcontent['keyword4'] = date('Y-m-d H:i:s',$commission_record['createtime']);//分销时间
                    $rs = \app\common\Wechat::sendtmpl($aid,$commission_record['mid'],'tmpl_fenxiaosuccess',$tmplcontent,m_url('pages/my/usercenter', $aid));
                    //短信通知
                    //$tel = Db::name('member')->where('id',$commission_record['mid'])->value('tel');
                    //$rs = \app\common\Sms::send($aid,$tel,'tmpl_fenxiaosuccess');
                }

            }
        }

		return ['status'=>1,'msg'=>'操作成功'];
	}

    //重新计算分成
    public static function updateCommission($orderGoods, $refundOrderGoods)
    {
        $newkey = 'ogid';
        $refundOrderGoods = collect($refundOrderGoods)->dictionary(null,$newkey);
        $ogids = array_keys($refundOrderGoods);
        foreach ($orderGoods as $og) {
            if(in_array($og['id'], $ogids)) {
                $new = [];
                if($og['parent1'] && ($og['parent1commission'] || $og['parent1score'])) {
                    $record = [];
                    if($og['parent1commission']) {
                        $new['parent1commission'] = $og['parent1commission'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['commission'] = $new['parent1commission'];
                    }
                    if($og['parent1score']) {
                        $new['parent1score'] = $og['parent1score'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['score'] = $new['parent1score'];
                    }
                    if($record) {
                        Db::name('member_commission_record')->where('mid',$og['parent1'])->where('aid',$og['aid'])->where('orderid',$og['orderid'])
                            ->where('ogid', $og['id'])->where('type', 'shop')->update($record);
                    }
                }
                if($og['parent2'] && ($og['parent2commission'] || $og['parent2score'])) {
                    $record = [];
                    if($og['parent2commission']) {
                        $new['parent2commission'] = $og['parent2commission'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['commission'] = $new['parent2commission'];
                    }
                    if($og['parent2score']) {
                        $new['parent2score'] = $og['parent2score'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['score'] = $new['parent2score'];
                    }
                    if($record) {
                        Db::name('member_commission_record')->where('mid',$og['parent2'])->where('aid',$og['aid'])->where('orderid',$og['orderid'])
                            ->where('ogid', $og['id'])->where('type', 'shop')->update($record);
                    }
                }
                if($og['parent3'] && ($og['parent3commission'] || $og['parent3score'])) {
                    $record = [];
                    if($og['parent3commission']) {
                        $new['parent3commission'] = $og['parent3commission'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['commission'] = $new['parent3commission'];
                    }
                    if($og['parent3score']) {
                        $new['parent3score'] = $og['parent3score'] / $og['num'] * ($og['num'] - $og['refund_num']);
                        $record['score'] = $new['parent3score'];
                    }
                    if($record) {
                        Db::name('member_commission_record')->where('mid',$og['parent3'])->where('aid',$og['aid'])->where('orderid',$og['orderid'])
                            ->where('ogid', $og['id'])->where('type', 'shop')->update($record);
                    }
                }
                if($new)
                    Db::name('shop_order_goods')->where('id', $og['id'])->update($new);
            }
        }
    }
}
